package com.kzw.oa.system.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.system.model.Department;

@Service
@Transactional
public class DepartmentService extends DefaultEntityManager<Department, Long> {

	/**
	 * 删除某个组织及其下属组织
	 * */
	public void removeAllCascade(long orgId) {		
		Department org = get(orgId);
		if(StringUtils.isNotBlank(org.getPath())) {
			List<Department> listOrgs = getByPath(org.getPath());
			for(Department o : listOrgs){
				o.setOrgSupId(-1L);
				o.setDepth(-1L);
				o.setPath("");
				saveOrUpdate(o);
			}
		}		
		org.setOrgSupId(-1L);
		org.setDepth(-1L);
		org.setPath("");
		saveOrUpdate(org);
	}
	
	/**
	 * 按路径查找所有节点
	 */
	@Transactional(readOnly=true)
	public List<Department> getByPath(String path){
		String hql = "from Department p where p.path like ? order by sn desc, createtime asc";
		return findByHQL(hql, path+"%");
	}
	
	/**
	 * 取得某个节点下的所有子节点
	 */
	public List<Department> getByParent(Long parentId){
		String hql="from Department p where p.orgSupId=? order by sn asc, createtime asc";
		return findByHQL(hql, parentId);
	}
}
